package action.system;

import java.io.File;
import java.util.Iterator;
import java.util.List;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import procomponent.Excelformat;
import services.system.FileloadServices;
import com.Const;
import com.PublicSystem;
import com.util.Component;
/**
* PersonMgrFacade:文件上传
* @author bjh
* @version Fri May 06 17:59:17 CST 2016 gjx
* @since 1.0
*/
@Controller
@RequestMapping("file.do")
public class FileloadAction extends HttpServlet {	
	PublicSystem sys = PublicSystem.getInstance();
	FileloadServices ls = new FileloadServices();
	private static final long serialVersionUID = 1L;
	/**
	 *  上传文件
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(params = "method=dofile")
	public void dofile(HttpServletRequest request, HttpServletResponse response) throws Exception {
		//创建一个通用的多部分解析器  
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        //判断 request 是否有文件上传,即多部分请求  
        if(multipartResolver.isMultipart(request)) {
        	//转换成多部分request
	        MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
	        //取得request中的所有文件名  
	        Iterator<String> iter = multiRequest.getFileNames();
	        int i = 1;
	        String czr = Component.getSession("userid", request);
	        while(iter.hasNext()) {
	        	//记录上传过程起始时的时间，用来计算上传时间  
	        	int pre = (int) System.currentTimeMillis();
	        	//取得上传文件  
	        	MultipartFile file = multiRequest.getFile(iter.next());
	        	if(file != null) {
	            	//取得当前上传文件的文件名称 
	            	 String FileName = file.getOriginalFilename();
	             	//如果名称不为“”,说明该文件存在，否则说明该文件不存在  
		            if(FileName.trim() != "") {
		                System.out.println(FileName);
		                //定义上传路径  
		                String path = Const.server_path+"/" + FileName;
		                File localFile = new File(path);
		                file.transferTo(localFile);
		                List list = Excelformat.readExcel(localFile);
		                ls.insertsql(list, "01", czr);
		             }
	            }
	            //记录上传该文件后的时间  
	            int finaltime = (int) System.currentTimeMillis();
	            System.out.println(finaltime - pre);
	        }	
         }
    }
}
